<?php

namespace app\admin\model;

use think\Model;


class FeedbackModel extends Model
{


    // 表名
    protected $name = 'feedback';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 追加属性
    protected $append = [
        //'type_text',
        'create_time_text',
        //'reply_time_text'
    ];

    public static function init()
    {
        self::beforeUpdate(function ($model) {
            if ($model->status == 0 && !empty($model->recontent)) {
                $model->status = 1;
                $model->reply_time = time();
            }
        });

    }


    public function getTypeListAttr()
    {
        return (new ConfigValueModel)->getOptionList(ConfigValueModel::TYPE_FEEDBACK);
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $data['type'] ?? '';
        return is_numeric($value) ? ConfigValueModel::where('cid', 1)
            ->where('option_id', $value)->value('option_name') : $value;
    }

    public function getStatusList()
    {
        return [0 => '未处理', 1 => '已处理'];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $data['status'] ?? '';
        return $this->getStatusList()[$value] ?? '未知';
    }

    public function getImagesAttr($value, $data)
    {
        $value = $value ?: ($data['images'] ?? []);
        $images = $value ? json_decode($value, true) : [];
        foreach ($images as $k =>$v) {
            $images[$k] = cdnurl($v);
        }
        return $images;
    }

    public function setImagesAttr($value)
    {
        if (empty($value)) return null;
        if (is_string($value)) {
            $value = explode(',', $value);
        }
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getReplyTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['reply_time']) ? $data['reply_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setReplyTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
